#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

class String
{
public:
	String()
    : _pstr(nullptr)
    /* : _pstr(new char[1]()) */
    {
        cout << "String()" << endl;
    }
	String(const char *pstr)
    : _pstr(new char[strlen(pstr) + 1]())
    {
        cout << "String(const char *)" << endl;
        strcpy(_pstr, pstr);
    }

	String(const String &rhs)
    : _pstr(new char[strlen(rhs._pstr) + 1]())
    {
        cout << "String(const String &)" << endl;
        strcpy(_pstr, rhs._pstr);

    }

	String &operator=(const String &rhs)
    {
        cout << "String &operator=(const String &)" << endl;
        if(this != &rhs)//1、自复制
        {
            delete [] _pstr;//2、释放左操作数
            _pstr = nullptr;

            //3、深拷贝
            _pstr = new char[strlen(rhs._pstr) + 1]();
            strcpy(_pstr, rhs._pstr);
        }

        return *this;//4、返回*this
    }

	~String()
    {
        cout << "~String()" << endl;
        if(_pstr)
        {
            delete [] _pstr;
            _pstr = nullptr;
        }
    }

	void print() const
    {
        if(_pstr)
        {
            cout << "_pstr = " <<_pstr << endl;
        }
    }

    size_t length() const
    {
        return strlen(_pstr);
    }

    const char * c_str() const
    {
        return _pstr;
    }

private:
	char *_pstr;
};

int main()
{
    //增量开发
	String str1;//默认构造函数
	str1.print();

    cout << endl;
	String str2 = "Hello,world";//String("Hello,world")
	String str3("wangdao");//普通构造函数
	
	str2.print();		
	str3.print();	
	
    cout << endl;
	String str4 = str3;//拷贝构造函数
	/* String str4(str3);//拷贝构造函数 */
	str4.print();
	
    cout << endl;
	str4 = str2;//赋值运算符函数
	str4.print();
	
	return 0;
}
